<template>
  <!-- 筛选条件集合 -->
  <div class="search-cmp-container">
    <div class="search-array-box">
      <div class="search-array-cmp">
        <el-select
          v-model="searchCmpValue"
          placeholder="请选择"
          style="width: 115px; margin-right: 1px"
        >
          <el-option
            v-for="(item, index) in searchCmpArray"
            :key="index"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <!-- 搜索组件（输入框、下拉框、日期等） -->
        <div class="seach-type-cmp">
          <!-- 关键词 -->
          <div class="keywords-search" v-if="curSearchType === 'keywords'">
            <el-input
              v-model="searchForm[searchCmpValue]"
              placeholder="输入内容标题或正文关键词"
              @keyup.enter="onSubmit"
              clearable
            />
          </div>
          <!-- 部门 -->
          <RuifoxDepart
            class="ruifox-depart"
            style="width: 700px"
            :field="searchCmpValue"
            v-else-if="curSearchType === 'depart'"
            v-model:value="departValue"
            :options="curOptions['depart']"
            @getValue="getDepartValue"
          />
          <!-- 栏目 -->
          <RuifoxCategory
            v-else-if="curSearchType === 'category'"
            v-model:value="searchForm[searchCmpValue]"
          />
          <!-- 发布日期 -->
          <div
            class="time-search content-search-box"
            v-else-if="curSearchType === 'datetime'"
          >
            <el-date-picker
              clearable
              v-model="searchForm[searchCmpValue]"
              type="daterange"
              range-separator="至"
              start-placeholder="编辑日期"
              end-placeholder="编辑日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :unlink-panels="true"
            />
          </div>
          <!-- 图片张数 -->
          <div
            v-else-if="curSearchType === 'count'"
            class="count-range content-search-box"
          >
            <el-input-number
              v-model="searchForm[searchCmpValue][0]"
              class="mx-4"
              :min="0"
              :max="searchForm[searchCmpValue][1]"
              controls-position="right"
              :controls="false"
              clearable
            />
            <span>&nbsp;-&nbsp;</span>
            <el-input-number
              v-model="searchForm[searchCmpValue][1]"
              class="mx-4"
              :min="searchForm[searchCmpValue][0]"
              controls-position="right"
              :controls="false"
              clearable
            />
          </div>
          <!-- 单选和多选 -->
          <div
            v-else-if="
              curSearchType === 'select' || curSearchType === 'multiple'
            "
            class="content-search-box"
            style="width: 100%"
          >
            <el-select
              v-model="searchForm[searchCmpValue]"
              clearable
              placeholder="请选择"
              style="width: 320px"
              :multiple="curSearchType === 'multiple' ? true : false"
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="option in curOptions[searchCmpValue]"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              >
                <span v-if="option.num">{{
                  `${option.label}（${option.num}）`
                }}</span>
                <span v-else>{{ `${option.label}` }}</span>
              </el-option>
            </el-select>
          </div>
          <el-tree-select
            v-else-if="curSearchType === 'treeSelect'"
            v-model="searchForm[searchCmpValue]"
            :data="curOptions[searchCmpValue]"
            filterable
            clearable
            placeholder="请选择"
            style="width: 320px"
            :node-key="curSearchObj.nodeKey"
            check-strictly
            :render-after-expand="false"
            :props="curSearchObj.props"
            ref="treeSelectRef"
            default-expand-all
            @node-click="(val) => handleAreaNodeClick(searchCmpValue, val)"
          />
          <el-cascader
            v-else-if="curSearchType === 'cascader'"
            v-model="searchForm[searchCmpValue]"
            :options="curOptions[searchCmpValue]"
            placeholder="请选择"
            clearable
            :props="cascaderProps"
            @change="handleCascaderChange"
          />
          <div
            v-else-if="curSearchType === 'switch'"
            class="content-search-box"
          >
            <el-switch
              v-model="searchForm[searchCmpValue]"
              inline-prompt
              active-text="有"
              inactive-text="无"
            />
          </div>
          <div class="content-search-box" v-else>
            <el-input
              v-model="searchForm[searchCmpValue]"
              placeholder="请输入关键词"
              @keyup.enter="onSubmit"
              clearable
            />
          </div>
        </div>
      </div>
      <div class="btns">
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </div>
    </div>
    <div class="search-tags">
      <el-tag
        v-for="tag in searchTagsList"
        :key="tag.key"
        @close="handleClearTag(tag)"
        closable
        effect="plain"
        type="info"
      >
        <div class="label">{{ `${tag.label}：` }}</div>
        <div
          class="value"
          v-if="['depart'].indexOf(tag.type) != -1"
          :title="tag.value"
        >
          {{ departLabel }}
        </div>
        <div
          class="value"
          v-else-if="['cascader'].indexOf(tag.type) != -1"
          :title="tag.value"
        >
          {{ toShowCascader(tag) }}
        </div>
        <div
          class="value"
          v-else-if="['select', 'multiple'].indexOf(tag.type) != -1"
          :title="tag.value"
        >
          {{ toShowLabelSelect(tag) }}
        </div>
        <div
          class="value"
          v-else-if="['treeSelect'].indexOf(tag.type) != -1"
          :title="tag.value"
        >
          {{ treeSelectLableObj[tag.key] || tag.key }}
        </div>
        <div class="value" v-else :title="tag.value">{{ `${tag.value}` }}</div>
      </el-tag>
      <el-button
        class="reset-btn"
        v-if="searchTagsList?.length > 0"
        type="primary"
        @click="reset"
        link
        >清空筛选条件</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { watch } from "vue";
const cascaderProps = {  
  // multiple: true,
  checkStrictly: true, 
}
const props = defineProps({
  // searchCmpValue数组对象参数示例[{
  //   lable: '作者',
  //   key: 'author',
  //   form_type: 'author',
  //   options:[] //下拉框时使用
  // }]
  searchCmpArray: {
    type: Array,
    default: () => {
      return [];
    },
  },
  searchForm: {
    type: Object,
    default: () => {
      return {};
    },
  },
  keyId: {
    type: [String, Number],
    default: "",
  },
});

const searchCmpValue = ref(props.searchCmpArray[0].key);
const searchCmpArray = computed(() => {
  return props.searchCmpArray;
});

const searchForm = computed(() => {
  return props.searchForm;
});
// 所有字典对象
const curOptions = computed(() => {
  let option = {};
  searchCmpArray.value.forEach((item) => {
    if (item.options) {
      option = {
        ...option,
        [item.key]: item.options,
      };
    }
  });
  return option;
});
// 获取当前筛选条件组件
const curSearchObj = computed(() => {
  let obj = searchCmpArray.value.find(
    (item) => item.key === searchCmpValue.value
  );
  return obj;
});
// 获取当前筛选条件组件（树形的props）
const curTreeSelectLabelKey = computed(() => {
  let obj = searchCmpArray.value.find(
    (item) => item.key === searchCmpValue.value
  )?.props;
  return obj;
});
// 获取当前筛选条件组件key
const curSearchType = computed(() => {
  let obj = searchCmpArray.value.find(
    (item) => item.key === searchCmpValue.value
  );
  return obj ? obj.form_type : obj.key;
});
const departValue = ref([]);
const departLabel = ref("");
const _departLabel = ref("");
const getDepartValue = (val) => {
  searchForm.value[val.field] = val.value;
  // _departLabel.value = val.showLabel.join(', ') //反显部门名称
};

const getLabelById = (treeData, id) => {
  if (!treeData || !treeData.length) return null;
  for (const item of treeData) {
    // 检查当前节点
    if (item.value === id) {
      return item.label;
    }
    // 递归检查子节点
    if (item.children && item.children.length) {
      const result = getLabelById(item.children, id);
      if (result) return result;
    }
  }
  return null; // 未找到匹配项
};
// 返显级联选择器
const toShowCascader = (tag) => { 
  console.log("tag",tag);
  if (tag){
    let result = getLabelById(curOptions.value[tag.key], tag.value) || '未找到'
    return result
  }
};

// 反显单选多选label
const toShowLabelSelect = (tag) => {
  if (Array.isArray(tag.value)) {
    //多选
    let arr = [];
    tag.value.forEach((item) => {
      let obj = curOptions.value[tag.key].find((ele) => ele.value == item);
      arr.push(obj?.label || "错误");
    });
    return arr.join(", ");
  } else {
    //单选
    return (
      curOptions.value[tag.key].find((item) => item.value == tag.value)
        ?.label || "错误"
    );
  }
};
// 反显树形单选label
const treeSelectRef = ref();
// const toShowLabelTreeSelect = (tag) => {
//   tag

//   return '-'
// }
// 反显树形单选label
const treeSelectLableObj = ref({});
const handleAreaNodeClick = (key, val) => {
  treeSelectLableObj.value[key] = val[curTreeSelectLabelKey.value.label];
};
// 清除指定条件tag
const handleClearTag = (val) => {
  if (typeof val["key"] === "boolean") {
    searchForm.value[val["key"]] = false;
  } else if (typeof val["key"] === "string") {
    searchForm.value[val["key"]] = "";
  } else if (typeof val["key"] === "object") {
    searchForm.value[val["key"]] = "";
  } else {
    searchForm.value[val["key"]] = null;
  }
  if (val["key"] == "depart") {
    departValue.value = [];
    searchForm.value["depart"] = [];
  }
  onSubmit();
};

// 重置清空检索表单的函数
const clearForm = (obj) => {
  for (let key in obj) {
    let objExit = searchCmpArray.value.find((ele) => ele.key == key);
    if (objExit) {
      if (Object.prototype.toString.call(obj[key]) === "[object Boolean]") {
        obj[key] = false;
      } else if (
        Object.prototype.toString.call(obj[key]) === "[object String]"
      ) {
        obj[key] = "";
      } else if (
        Object.prototype.toString.call(obj[key]) === "[object Object]"
      ) {
        obj[key] = null;
      } else if (
        Object.prototype.toString.call(obj[key]) === "[object Array]"
      ) {
        obj[key] = [];
      } else {
        obj[key] = null;
      }
    }
  }
};
// 清空
const reset = () => {
  departValue.value = [];
  clearForm(searchForm.value);
  onSubmit();
};
const showTags = () => {
  // 显示所有的筛选条件tags
  searchTagsList.value = [];
  for (const key in searchForm.value) {
    const item = searchForm.value[key];
    if (
      item != undefined &&
      item !== "" &&
      !Array.isArray(item) || (Array.isArray(item) && item.length > 0) &&
      ["total", "pageSize", "currentPage"].indexOf(key) == -1
    ) {
      let obj = searchCmpArray.value.find((ele) => ele.key == key);
      if (obj) {
        searchTagsList.value.push({
          key,
          type: obj?.form_type,
          label: obj?.label || "-",
          value: item,
        });
      }
    }
  }
  departLabel.value = _departLabel.value;
};
const emits = defineEmits(["onSubmit"]);
// 搜索
const searchTagsList = ref([]);
const onSubmit = () => {
  showTags();
  emits("onSubmit");
};

defineExpose({
  clearForm,
  showTags,
});

watch(
  searchForm,
  () => {
    showTags();
  },
  { deep: true }
);
</script>
<style scoped lang="scss">
.search-cmp-container {
  .search-array-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .btns {
      margin-left: 10px;
    }
    .search-array-cmp {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .keywords-search {
        width: 760px;
      }
      .content-search-box {
        width: 320px;
      }
      .time-search {
        ::v-deep(.el-date-editor.el-input__wrapper) {
          width: 320px;
          box-sizing: border-box;
        }
      }
      ::v-deep(.ruifox-depart) {
        .depart-select {
          min-height: 32px;
        }
        .depart-container {
          min-height: initial;
          .chose-depart {
            margin: 0 10px;
          }
        }
      }
    }
  }
  .search-tags {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    ::v-deep(.el-tag) {
      width: fit-content;
      margin-right: 10px;
      margin-top: 10px;
      .el-tag__content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
      }
      .label {
        // color: #999;
      }
      .value {
        color: #333;
        display: inline-block;
        width: fit-content;
        max-width: 500px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .reset-btn {
      margin-top: 10px;
    }
  }
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
